<?php
require_once($_SERVER['DOCUMENT_ROOT'].'../system/config.php');

// check for username
if (isset($_REQUEST['username'])) {
	$username = $_REQUEST['username'];
}
else {
	header('HTTP/1.1 400 Bad Request');
	die('Missing required field: username');
}

// check for password
if (isset($_REQUEST['password'])) {
	$password = md5($_REQUEST['password']);
}
else {
	header('HTTP/1.1 400 Bad Request');
	die('Missing required field: password');
}

// open database
$db = new PDO("sqlite:".$DATABASE);

$query = "SELECT username, usergroup FROM user WHERE username = :user AND password = :pass";
$select = $db->prepare($query);
if (!$select)  {
	header('HTTP/1.1 500 Internal Server Error');
	die('there is a problem with the database');
}
else {
	$select->execute(array(':user'=>$username, ':pass'=>$password));
	$row = $select->fetch(PDO::FETCH_ASSOC);
	if (!$row || count($row) < 2) {
		header('HTTP/1.1 401 Unauthorized');
		die('User could not be authenticated.');
	}
	// redundant check...
	else if ($row['username'] != $username) {
		header('HTTP/1.0 401 Unauthorized');
		die('User could not be authenticated.');
	}
	else {
		$username = $row['username'];
		$groupname = $row['usergroup'];
	}

}
$db = null;

require_once $INCLUDE_DIR.'cametrics.helper.php';
$url = Cametrics::getURL();

$usercount = file_get_contents($url."$username/contributions/type/stats/count");
$userlist = json_decode(file_get_contents($url."$username/contributions/type/stats/hits"), true);
$numcategory = count($userlist);
$worldcount = file_get_contents($url."contributions/stats/count");

if (!is_numeric($usercount)) {
	$usercount = 0;
}
?>
<html>
<head>
	<link rel="stylesheet" href="<?=$CSS_DIR?>blueprint/miniscreen.css" type="text/css" media="screen, projection" />
	 <!--[if IE]><link rel="stylesheet" href="<?=$CSS_DIR?>blueprint/ie.css" type="text/css" media="screen, projection" /><![endif]-->
	<link rel="stylesheet" href="<?=$CSS_DIR?>main.css" type="text/css">

	<!-- for iphone -->
	
	<meta name="viewport" content="width=device-width; initial-scale=.8; maximum-scale=1.0; user-scalable=0;" />
</head>
<body>
<div class="container">
<div class="span-8 last">
		<h3 class="center">Welcome <?php echo $username; ?>, here are your specific stats. Have fun!</h3>
	<hr />

	<div class="span-4">
		<h3 class="center">Number of Images:</h3>
		<h3 class="color5 center"><?= $usercount ?></h3>
	</div>
	<div class="span-4 last">
		<h3 class="center">Percent Contributed:</h3>
			<h3 class="color5 center">
		<?php if ($worldcount): ?>
			<?= round($usercount / $worldcount, 2) * 100 ?>%
		<?php endif ?>
		</h3>
	</div>

	<div class="span-8 center last">
		<h3 class="center">Submissions:</h3>
<?php if ($usercount > 0): ?>
		<img src="<?= $url ?><?= $username ?>/contributions/type/stats/hits.gc?cht=bhs&chbh=a&chs=200x<?=$numcategory*25?>&chco=8F4B21"/>
<?php else: ?>
		<h3 class="color5 center">No Submissions yet.</h3>
<?php endif; ?>
	</div>
</div>
</div>
</body>
</html>
